<?php declare(strict_types=1);
/**
 * @author      xianganyall <xianganyall@gmail.com>
 * @copyright   2023-2025 owner
 **/

namespace Srv\Libs\Storage;

use Smarty_CacheResource_KeyValueStore;
use Srv\Libs\Frame\ControllerAbstract;

final class SmartyCacheRedis extends Smarty_CacheResource_KeyValueStore
{
    /**
     * @param array $keys
     * @return array
     * read
     */
    protected function read(array $keys):array
    {
        $valList                = [];
        if(count($keys) > 0){
            $DataRedis          = ControllerAbstract::getCacheAuto();
            foreach($keys as $key) $valList[$key] = $DataRedis->get($this->getKeyName($key));
        }
        return $valList;
    }

    /**
     * @param array $keys
     * @param $expire
     * @return bool
     * write
     */
    protected function write(array $keys, $expire = null):bool
    {
        if(count($keys) > 0){
            $expire             = intval($expire);
            $DataRedis          = ControllerAbstract::getCacheAuto();
            foreach($keys as $key => $val) $DataRedis->set($this->getKeyName($key), $val, $expire);
        }
        return true;
    }

    /**
     * @param array $keys
     * @return bool
     * delete
     */
    protected function delete(array $keys):bool
    {
        if(count($keys) > 0){
            $DataRedis          = ControllerAbstract::getCacheAuto();
            foreach($keys as $key) $DataRedis->del($this->getKeyName($key));
        }
        return true;
    }

    /**
     * @return bool
     * purge
     */
    protected function purge():bool
    {
        return true;
    }

    /**
     * @param string $key
     * @return string
     * getKeyName
     */
    private function getKeyName(string $key):string
    {
        return 'SMARTY_REDIS_'.md5($key);
    }
}